package cn.cai.pethome.dept.controller;

import cn.cai.pethome.base.util.AjaxResult;
import cn.cai.pethome.base.util.PageList;
import cn.cai.pethome.dept.domain.Department;
import cn.cai.pethome.dept.query.DepartmentQuery;
import cn.cai.pethome.dept.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
@Api(value = "部门的API", description = "部门相关的CRUD功能")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;



    @GetMapping("/deptAll")
    @ApiOperation(value = "查询所以数据")
    public List<Department> querydept(){
        return departmentService.findAll();
    }

    /**
     * 查询一个数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询部门")
    public Department queryDepartment(@PathVariable("id") Long id) {
        return departmentService.findById(id);
    }


    @GetMapping
    @ApiOperation(value = "查询部门树")
    public List<Department> detpTree(){
       return departmentService.getTree();
    }

    /**
     * 高级查询
     *
     * @param query
     * @return
     */
    @PostMapping
    @ApiOperation(value = "部门的高级查询" )
    public PageList<Department> queryDepartment(@RequestBody DepartmentQuery query) {

        return departmentService.queryAll(query);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除部门" )
    public AjaxResult department(@PathVariable("id") Long id) {

        try {

            departmentService.deleteById(id);
            return AjaxResult.me();  //成功之后调用AjaxResult中的success
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    /**
     * 添加或者修改
     *
     * @param department
     */
    @PutMapping
    @ApiOperation(value = "添加或者修改部门 如果id为null则添加否则修改" )
    public AjaxResult department(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                departmentService.add(department);
            } else {

                departmentService.update(department);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @PatchMapping
    @ApiOperation(value = "批量删除数据" )
    public AjaxResult dept(@RequestBody List<Long> ids){
        try {
            departmentService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.error();
        }
    }


}
